import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/user/wallet_model_entity.dart';
import 'package:xvideos/hj_page/mine_business/make_money/withdrawal_logic.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';

import '../../../assets_tool/app_colors.dart';
import '../mine_utils.dart';
import 'in_come_entity.dart';
import 'mine_withdrawal_record_page.dart';

//我要提现页面
class WithdrawalPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetBuilder<WithdrawalLogic>(
      init: WithdrawalLogic(),
      builder: (logic) {
        return Scaffold(
            appBar: AppBar(
              title: Text(
                '我要提现',
                style: TextStyle(
                  color: Color(0xE5FFFFFF),
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
              actions: <Widget>[
                GestureDetector(
                  child: Text(
                    '明细',
                    style: TextStyle(color: Color(0x73FFFFFF), fontSize: 12),
                  ),
                  onTap: () => Get.to(RecordsPage(RecordType.withdraw)),
                ),
                16.w.sizeBoxW,
              ],
            ),
            body: () {
              if (logic.isLoading) return LoadingCenterWidget();
              if (logic.configData == null) return CErrorWidget();
              TextStyle _style = const TextStyle(fontSize: 14);
              var textPainter = TextPainter(
                text: TextSpan(
                  text: '',
                  style: _style,
                ),
                textDirection: TextDirection.ltr,
                textWidthBasis: TextWidthBasis.longestLine,
              )..layout();

              return Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
                      child: Container(
                        margin: EdgeInsets.only(left: 16.w, right: 16.w),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                                margin: EdgeInsets.only(top: 12.w, bottom: 18.w),
                                padding: EdgeInsets.symmetric(vertical: 12.w),
                                decoration: BoxDecoration(
                                  color: Color(0x0DFFFFFF),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Column(
                                  children: [
                                    Row(
                                      children: [
                                        Container(
                                          height: 22,
                                          width: 8,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.only(
                                              topRight: Radius.circular(11),
                                              bottomRight: Radius.circular(11),
                                            ),
                                            color: AppColors.primaryXColor,
                                          ),
                                        ),
                                        12.sizeBoxW,
                                        Text(
                                          "余额(元)",
                                          style: const TextStyle(
                                            color: AppColors.primaryXColor,
                                            fontWeight: FontWeight.w400,
                                            fontSize: 14.0,
                                          ),
                                        ),
                                      ],
                                    ),
                                    12.sizeBoxH,
                                    Padding(
                                      padding: EdgeInsets.only(left: 20),
                                      child: Row(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          Image.asset('coin_icon.png'.mineImgPath, width: 30),
                                          4.sizeBoxW,
                                          Consumer<GlobalStore>(builder: (_, store, __) {
                                            logic.userIncomeModel = store.wallet;
                                            return ShaderMask(
                                                shaderCallback: (Rect bounds) {
                                                  return LinearGradient(
                                                    colors: [Color(0xffFFE8BE), Color(0xffE6B764)],
                                                    tileMode: TileMode.mirror,
                                                  ).createShader(Offset.zero & bounds.size);
                                                },
                                                blendMode: BlendMode.srcATop,
                                                child: Container(
                                                  child: Text(
                                                    ((store.wallet?.walletBalance() ?? 0) * 10 / 100).toStringAsFixed(2),
                                                    style: const TextStyle(
                                                      fontWeight: FontWeight.w500,
                                                      fontSize: 32,
                                                    ),
                                                  ),
                                                ));
                                          }),
                                        ],
                                      ),
                                    ),
                                  ],
                                )),
                            Row(
                              children: [
                                Text(
                                  '提现币类:',
                                  style: textStyle(14, Color(0xE5FFFFFF), FontWeight.w500),
                                ),
                                15.sizeBoxW,
                                Text(
                                  '人民币',
                                  style: textStyle(14, Color(0x8CFFFFFF), FontWeight.w400),
                                ),
                              ],
                            ),
                            16.sizeBoxH,
                            Row(
                              children: [
                                Text(
                                  "提现金额:",
                                  style: textStyle(14, Color(0xE5FFFFFF), FontWeight.w500),
                                ),
                                10.sizeBoxW,
                                Expanded(
                                  child: Container(
                                    alignment: Alignment.centerLeft,
                                    height: 40,
                                    padding: EdgeInsets.symmetric(horizontal: 12),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(.05),
                                      borderRadius: BorderRadius.circular(6),
                                    ),
                                    child: TextField(
                                        inputFormatters: [
                                          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                                          LengthLimitingTextInputFormatter(9),
                                        ],
                                        controller: logic.moneyController,
                                        style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w400),
                                        cursorColor: Colors.white.withOpacity(0.7),
                                        decoration: InputDecoration(
                                          border: InputBorder.none,
                                          contentPadding: EdgeInsets.only(bottom: 8),
                                          hintStyle: TextStyle(color: Color(0xFF525252), fontSize: 12, fontWeight: FontWeight.w400),
                                          hintText: '单笔提现金额范围 ${_getPayMoneyRange(logic)}元', //"您目前
                                        ),
                                        focusNode: logic.focusNode,
                                        onChanged: (value) => logic.calcWithdrawAmount(value)),
                                  ),
                                )
                              ],
                            ),
                            16.sizeBoxH,
                            Row(
                              children: [
                                Text(
                                  "提现方式:",
                                  style: textStyle(14, Color(0xE5FFFFFF), FontWeight.w500),
                                ),
                                16.sizeBoxW,
                                Expanded(
                                  child: SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: Container(
                                      height: 30,
                                      child: Row(
                                        children: logic.configData?.realChannel
                                                .asMap()
                                                .map((index, e) => MapEntry(index, _buildPayTypeUI(e, logic, index)))
                                                .values
                                                .toList() ??
                                            [],
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            16.sizeBoxH,
                            Row(
                              children: [
                                if (_isUsdt(logic)) ...[
                                  Text(
                                    'USDT地址:',
                                    style: textStyle(14, Color(0xE5FFFFFF), FontWeight.w500),
                                  ),
                                  10.sizeBoxW,
                                  Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        color: Colors.white.withOpacity(.05),
                                        borderRadius: BorderRadius.circular(6),
                                      ),
                                      child: TextField(
                                        textAlignVertical: TextAlignVertical.center,
                                        controller: logic.accountController,
                                        maxLines: 1,
                                        decoration: InputDecoration(
                                          border: InputBorder.none,
                                          hintText: _getHintText(logic),
                                          hintStyle: TextStyle(color: Color(0xff999999), fontSize: 14, fontWeight: FontWeight.w400),
                                          isCollapsed: true,
                                          contentPadding: EdgeInsets.symmetric(
                                            horizontal: 12,
                                            vertical: (32 - textPainter.height) / 2,
                                          ),
                                        ),
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 14,
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ),
                                  )
                                ] else ...[
                                  Text(
                                    '银行卡号:',
                                    style: textStyle(14, Color(0xE5FFFFFF), FontWeight.w500),
                                  ),
                                  10.sizeBoxW,
                                  Expanded(
                                      child: InkWell(
                                    onTap: () => logic.gotoBankList(),
                                    child: Container(
                                      alignment: Alignment.centerLeft,
                                      height: 37,
                                      padding: EdgeInsets.only(left: 10),
                                      decoration: BoxDecoration(
                                        color: Colors.white.withOpacity(.05),
                                        borderRadius: BorderRadius.circular(6),
                                      ),
                                      child: Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              logic.bankModel == null
                                                  ? "请选择提现银行账号"
                                                  : "${logic.bankModel?.getBankName()}(${logic.bankModel?.act?.substring((logic.bankModel?.act?.length ?? 4) - 4)}) ${logic.bankModel?.actName}",
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: logic.bankModel == null ? Color(0xff525252) : Colors.white,
                                              ),
                                            ),
                                          ),
                                          6.sizeBoxW,
                                          Icon(Icons.keyboard_arrow_right, color: Colors.white, size: 16),
                                          10.sizeBoxW,
                                        ],
                                      ),
                                    ),
                                  )),
                                ]
                              ],
                            ),
                            16.sizeBoxH,
                            GetBuilder<WithdrawalLogic>(
                              init: logic,
                              id: 'money',
                              builder: (controller) => EasyRichText(
                                '手续费率:  ${logic.configData?.coinTax ?? 0}%   实际到账金额: ${logic.actualAmount}',
                                defaultStyle: textStyle(14, Color(0xE5FFFFFF), FontWeight.w500),
                                patternList: [
                                  EasyRichTextPattern(
                                    targetString: '${logic.configData?.coinTax ?? 0}%',
                                    style: TextStyle(
                                      fontSize: 12,
                                      fontWeight: FontWeight.w500,
                                      color: Color(0x8CFFFFFF),
                                    ),
                                  ),
                                  EasyRichTextPattern(
                                    targetString: '实际到账金额: ${logic.handlingFee}',
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                      color: Color(0x8CFFFFFF),
                                    ),
                                  ),
                                  EasyRichTextPattern(
                                    targetString: '${logic.actualAmount}',
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                      color: Color(0x8CFFFFFF),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            18.sizeBoxH,
                            Text(
                              "提现规则：",
                              style: const TextStyle(color: Color(0xE5FFFFFF), fontWeight: FontWeight.w500, fontSize: 16.0),
                            ),
                            12.sizeBoxH,
                            Text(
                              "1、每次提现金额最低${(logic.configData?.channels == null ? 0 : logic.selectChannel?.minMoney ?? 0) ~/ 100}元起，"
                              "单笔提现最大${(logic.configData?.channels == null ? 0 : logic.selectChannel?.maxMoney ?? 0) ~/ 100}元，且为整数。\n"
                              "2、每次提现收取${logic.configData?.coinTax}%手续费。\n"
                              "3、仅支持银行卡提现，收款账户卡号与姓名一致，到账时间未72小时内。\n"
                              "4、申请提现后请随时关注收款账户进款通知，长时间未到账，请及时联系客服。\n",
                              style:
                                  const TextStyle(color: const Color(0x8CFFFFFF), fontWeight: FontWeight.w400, fontSize: 12.0, height: 2),
                            ),
                            30.sizeBoxH,
                          ],
                        ),
                      ),
                    ),
                  ),
                  Column(
                    children: [
                      GestureDetector(
                        onTap: () => logic.submitWithdraw(),
                        child: Container(
                            height: 47,
                            alignment: Alignment.center,
                            margin: EdgeInsets.symmetric(horizontal: 40),
                            decoration: BoxDecoration(
                              color: AppColors.actionRed,
                              borderRadius: BorderRadius.circular(3),
                            ),
                            child: Text(
                              '立即提现',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            )),
                      ),
                      10.sizeBoxH,
                      EasyRichText(
                        '提现中如有问题，请联系 在线客服',
                        defaultStyle: textStyle(12, Colors.white, FontWeight.w400),
                        patternList: [
                          EasyRichTextPattern(
                            targetString: '在线客服',
                            style: TextStyle(color: Color(0xffFFD460)),
                            recognizer: TapGestureRecognizer()..onTap = MineUtils.goCSPage,
                          ),
                        ],
                      ),
                      34.sizeBoxH,
                    ],
                  )
                ],
              );
            }());
      },
    );
  }

  ///支付类型
  Widget _buildPayTypeUI(Channel channel, WithdrawalLogic logic, int index) {
    bool isSelected = logic.selectChannel?.payType == channel.payType;
    return InkWell(
      onTap: () => logic.changeWithdrawType(channel.payType ?? ''),
      child: Row(
        children: [
          Image.asset(channel.payType == 'usdt' ? 'ic_usdt.png'.mineImgPath : 'ic_union.png'.mineImgPath, width: 30),
          4.sizeBoxW,
          Text(_getPayTypeName(channel.payType ?? ""), style: TextStyle(color: Colors.white, fontSize: 14)),
          10.sizeBoxW,
          Image.asset(
            isSelected ? 'mine_withdraw_sel.png'.mineImgPath : 'mine_withdraw_nor.png'.mineImgPath,
            width: 24,
          ),
          24.sizeBoxW,
        ],
      ),
    );
  }

  ///获取支付方式名称
  String _getPayTypeName(String payType) {
    if ("alipay" == payType) {
      return "支付宝";
    } else if ("bankcard" == payType) {
      return "银行卡";
    } else if ("usdt" == payType) {
      return "USDT";
    }
    return "银行卡";
  }

  ///获取提现金额范围
  String _getPayMoneyRange(WithdrawalLogic logic) {
    try {
      int minMoney = logic.configData?.channels?[logic.withdrawType].minMoney ?? 0;
      int maxMoney = logic.configData?.channels?[logic.withdrawType].maxMoney ?? 0;
      return "${minMoney / 100}-${maxMoney / 100}";
    } catch (e) {}
    return "0";
  }

  String _getHintText(WithdrawalLogic logic) {
    int withdrawType = logic.withdrawType;
    List<Channel> channels = logic.configData?.channels ?? [];
    if (channels.isEmpty) return "";
    if ((channels[withdrawType].payType ?? "") == 'alipay') {
      return '请输入支付宝账号';
    } else if ((channels[withdrawType].payType ?? "") == 'bankcard') {
      return '请输入银行卡号';
    } else if ((channels[withdrawType].payType ?? "") == 'usdt') {
      return '请输入USDT地址';
    }
    return "";
  }

  bool _isUsdt(WithdrawalLogic logic) {
    int withdrawType = logic.withdrawType;
    List<Channel> channels = logic.configData?.channels ?? [];
    if (channels.isEmpty) {
      return false;
    }
    if ((channels[withdrawType].payType ?? "") == 'usdt') {
      return true;
    } else {
      return false;
    }
  }
}
